package ReadCommit.connection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;

public class SelectThread extends Thread implements ReadCommitSql {

    private static final Logger logger = LoggerFactory.getLogger(SelectThread.class);

    private final ConnectionInfo connectionInfo;

    public SelectThread(ConnectionInfo connectionInfo) {
        this.connectionInfo = connectionInfo;
    }
    static AtomicInteger time = new AtomicInteger(1);
    private int getBalanceSum() throws SQLException {
        int result  = 0;
        String randomId = "a" + getRandomId();
//        Statement statement = null;
//        Connection connection = null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd hh:mm:ss:SSS");
        try (Connection connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword());
            Statement statement = connection.createStatement()){
//            connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUsername(), connectionInfo.getPassword());
            connection.setAutoCommit(false);
//            statement = connection.createStatement();
//            System.out.println(selectBalanceSqlRight + randomId + selectBalanceSqlRight);
            ResultSet resultSet = statement.executeQuery(selectBalanceSqlLeft + randomId + selectBalanceSqlRight);
            int row = 1;
            while (resultSet.next()) {
                int col = resultSet.getInt(1);
                result += col;
                System.out.println(sdf.format(new Date(System.currentTimeMillis())) + " " + "第" + time + "次查， col" + row + " = " + col);
                logger.info("第" + time + "次查， id " + randomId +"， col" + row + " = " + col);
                row++;
            }
            if (result == 100) {
                System.out.println(sdf.format(new Date(System.currentTimeMillis())) + " " + "第" + time + "次查， 未出现异常: " + result);
                logger.info("第" + time + "次查， id " + randomId +"， 未出现异常: " + result);
            } else {
                System.err.println(sdf.format(new Date(System.currentTimeMillis())) + " " + "第" + time + "次查， 出现异常: " + result);
                logger.error("第" + time + "次查， id " + randomId +"， 出现异常: " + result);
            }
            time.getAndIncrement();
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
    public void run (){
        try {
            getBalanceSum();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
